package com.jiangxiaofei.citycloud.activity.village;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.OptionsPickerView;
import com.blankj.utilcode.util.EmptyUtils;
import com.jiangxiaofei.citycloud.R;
import com.jiangxiaofei.citycloud.adapter.VillagePublishHeaderPhotoAdapter;
import com.jiangxiaofei.citycloud.base.BaseActivity;
import com.jiangxiaofei.citycloud.bean.VillageDetailBean;
import com.jiangxiaofei.citycloud.constants.Constants;
import com.jiangxiaofei.citycloud.constants.StringConstants;
import com.jiangxiaofei.citycloud.mvp.MainConstant;
import com.jiangxiaofei.citycloud.mvp.MainPersenter;
import com.jiangxiaofei.citycloud.mvp.VillageConstant;
import com.jiangxiaofei.citycloud.mvp.VillagePersenter;
import com.jiangxiaofei.citycloud.param.UpLoadPhotoParam;
import com.jiangxiaofei.citycloud.param.VillageArticleParam;
import com.jiangxiaofei.citycloud.util.ImgUtils;
import com.jiangxiaofei.citycloud.util.PickerImageLoader;
import com.jiangxiaofei.citycloud.view.IOSAlertDialog;
import com.jiangxiaofei.citycloud.view.ProgressDialogHelper;
import com.jiangxiaofei.citycloud.view.RichEditor;
import com.lzy.imagepicker.ImagePicker;
import com.lzy.imagepicker.bean.ImageItem;
import com.lzy.imagepicker.ui.ImageGridActivity;
import com.lzy.imagepicker.view.CropImageView;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

/**
 * Created by JiangXFei on 2017/8/18.
 * 美丽乡村信息发布修改页面
 */

public class VillageInfoPublishActivity extends BaseActivity implements
        VillageConstant.VillageAddArticleView, VillageConstant.VillageUpdateArticleView, MainConstant.UpLoadPhotoView {
    public static final int IMAGE_PICKER = 0x0019;
    @InjectView(R.id.village_publish_et_title)
    EditText villagePublishEtTitle;  //标题
    @InjectView(R.id.village_publish_ret_content)
    RichEditor villagePublishRetContent; //内容
    @InjectView(R.id.village_publish_tv_position)
    TextView villagePublishTvPosition;// 位置
    @InjectView(R.id.village_publish_btn_post)
    Button villagePublishBtnPost;//修改提交按钮
    @InjectView(R.id.tv_add_photo)
    TextView villagePublishTvPhoto;//添加照片
    @InjectView(R.id.recy_photo_list)
    RecyclerView villagePublishRecyPhoto;//照片列表
    @InjectView(R.id.hsv_photo_list)
    HorizontalScrollView villagePublishHsv;
    @InjectView(R.id.village_publish_tv_select_type)
    TextView villagePublishTvSelectType;//文章类型
    @InjectView(R.id.img_add_photo_litter)
    ImageView villagePublishImgAddPhoto;//添加图片按钮


    //    /**
//     * 内容表单验证
//     */
//    public boolean isNullForm() {
//        if (StringUtil.isNotNull(villagePublishEtTitle.getText().toString()))
//            return false;
//    }
    public static final String PUBLISH = "PUBLISH";
    public static final String UPDATE = "UPDATE";
    public static final String ADDORUPDATE = "ADDORUPDATE";
    public static final String ARTICLEID = "ARTICLEID";
    public static final int resultCode = 0x0019;
    public static final int SHOWADDPHOTO = 0x0001;
    public static final int HIDEADDPHOTO = 0x0002;
    private VillagePublishHeaderPhotoAdapter photoAdapter;
    private OptionsPickerView optionsPickerView;
    private List<String> typeList;
    private VillageConstant.VillageAddArticlePersenter mVillageAddArticlePersenter;
    private VillageConstant.VillageUpdateArticlePersenter mVIllageUpdateActiclePersemter;
    VillageArticleParam param = new VillageArticleParam();
    List<String> imgList = new ArrayList<>();
    StringBuffer imgSb = new StringBuffer();
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case SHOWADDPHOTO:
                    //显示添加图片
                    villagePublishHsv.setVisibility(View.GONE);
                    villagePublishTvPhoto.setVisibility(View.VISIBLE);
                    break;
                case HIDEADDPHOTO:
                    villagePublishHsv.setVisibility(View.VISIBLE);
                    villagePublishTvPhoto.setVisibility(View.GONE);
                    int position = (int) msg.obj;
                    imgList.remove(position);
                    //隐藏添加图片
                    break;
                default:
                    break;
            }
        }
    };
    private Intent intent;
    private String addOrUpdate = "";
    private int categroyId;
    private int id;
    private MainConstant.UploadPhotoPersenter mUploadPhotosPersenter;
    private UpLoadPhotoParam photoParam;
    private VillageDetailBean detailBean;
    private ArrayList<ImageItem> images = new ArrayList<>();
    private String[] stringArray;
    private String city;
    private String district;

    @Override
    protected void initView(Bundle savedInstanceState) {
        mContext = this;
        mActivity = this;
        setContentView(R.layout.activity_village_info_publish_layout);
        ButterKnife.inject(this);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);//设置软件盘默认不弹出
        mVillageAddArticlePersenter = new VillagePersenter(mContext, (VillageConstant.VillageAddArticleView) mActivity);
        mVIllageUpdateActiclePersemter = new VillagePersenter(mContext, (VillageConstant.VillageUpdateArticleView) mActivity);
        mUploadPhotosPersenter = new MainPersenter(mContext, (MainConstant.UpLoadPhotoView) mActivity);
        intent = getIntent();
        addOrUpdate = intent.getStringExtra(StringConstants.PUBLISHTYPE);
        stringArray = getResources().getStringArray(R.array.village_menu);
        initTitle();
        initPicker();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false);
        villagePublishRecyPhoto.setLayoutManager(linearLayoutManager);
        if (EmptyUtils.isNotEmpty(addOrUpdate) && addOrUpdate.equals(UPDATE)) {
            detailBean = intent.getParcelableExtra(StringConstants.UPDATEBEAN);
            initUpdateData();
        }
    }

    private void initPicker() {
        ImagePicker imagePicker = ImagePicker.getInstance();
        imagePicker.setImageLoader(new PickerImageLoader());   //设置图片加载器
        imagePicker.setShowCamera(true);  //显示拍照按钮
        imagePicker.setCrop(true);        //允许裁剪（单选才有效）
        imagePicker.setSaveRectangle(true); //是否按矩形区域保存
        imagePicker.setSelectLimit(9);    //选中数量限制
        imagePicker.setStyle(CropImageView.Style.RECTANGLE);  //裁剪框的形状
        imagePicker.setFocusWidth(800);   //裁剪框的宽度。单位像素（圆形自动取宽高最小值）
        imagePicker.setFocusHeight(800);  //裁剪框的高度。单位像素（圆形自动取宽高最小值）
        imagePicker.setOutPutX(1000);//保存文件的宽度。单位像素
        imagePicker.setOutPutY(1000);//保存文件的高度。单位像素
    }

    private void initUpdateData() {
        villagePublishRetContent.setEditorFontSize(15);
        villagePublishRetContent.setPadding(10, 10, 10, 50);
        villagePublishRetContent.setPlaceholder("请输入内容：");
        villagePublishEtTitle.setText(detailBean.getTitle());
        villagePublishRetContent.setHtml(detailBean.getContent());
        villagePublishTvPosition.setText(detailBean.getLocaltion());
        villagePublishTvSelectType.setText(stringArray[detailBean.getCategory() - 1]);
        if (images.size() > 0) {
            images.clear();
        }
        for (int i = 0; i < ImgUtils.getImgs(detailBean.getImg()).size(); i++) {
            ImageItem item = new ImageItem();
            item.path = ImgUtils.getImgs(detailBean.getImg()).get(i);
            imgList.add(ImgUtils.getImgs(detailBean.getImg()).get(i));
            images.add(item);
        }
        if (images.size() > 0) {
            villagePublishHsv.setVisibility(View.VISIBLE);
            villagePublishTvPhoto.setVisibility(View.GONE);
        } else {
            villagePublishHsv.setVisibility(View.GONE);
            villagePublishTvPhoto.setVisibility(View.VISIBLE);
        }
        photoAdapter = new VillagePublishHeaderPhotoAdapter(mContext, images, handler);
        villagePublishRecyPhoto.setAdapter(photoAdapter);

        id = detailBean.getId();
        categroyId = detailBean.getCategory();
    }

    @Override
    protected void setListener() {
        mLeftOne.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.iv_leftone:
                //退出按钮
                exitDialog();
                break;
            default:
                break;
        }
    }

    //退出弹窗
    public void exitDialog() {
        IOSAlertDialog dialog = new IOSAlertDialog(mContext);
        dialog.builder();
        dialog.setTitle("退出编辑");
        dialog.setMsg("是否退出编辑页面？");
        dialog.setPositiveButton("退出", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mActivity.finish();
            }
        });
        dialog.setNegativeButton("取消", new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        dialog.show();
    }

    //设置头部信息
    @Override
    protected void processLogic(Bundle savedInstanceState) {
        if (addOrUpdate.equals(PUBLISH)) {
            setCTitle("信息发布");
            if (EmptyUtils.isNotEmpty(Constants.bdLocation)) {
                city = Constants.bdLocation.getCity();
                district = Constants.bdLocation.getDistrict();
            } else {
                city = "青岛市";
            }
            villagePublishTvPosition.setText(city + "" + district);
            villagePublishBtnPost.setText("发布");
        } else if (addOrUpdate.equals(UPDATE)) {
            setCTitle("文章修改");
            villagePublishBtnPost.setText("修改");
        }
        setLeftOneBg(R.drawable.ic_back);
    }

    @OnClick({R.id.village_publish_btn_post, R.id.tv_add_photo
            , R.id.img_add_photo_litter, R.id.village_publish_tv_select_type})
    public void OnClick(View v) {
        switch (v.getId()) {
            case R.id.village_publish_btn_post:
                //发布
                if (addOrUpdate.equals(PUBLISH)) {
                    imgSb = new StringBuffer();
                    param.setTitle(villagePublishEtTitle.getText().toString());
                    param.setContent(villagePublishRetContent.getHtml());
                    param.setCategory(categroyId);
                    param.setAuthor(Constants.userId);
                    param.setLocation(villagePublishTvPosition.getText().toString());
                    param.setImg(ImgUtils.getImgsString(imgList));
                    imgList.clear();
                    mVillageAddArticlePersenter.addVillageArticle();
                } else if (addOrUpdate.equals(UPDATE)) {
                    imgSb = new StringBuffer();
                    param.setTitle(villagePublishEtTitle.getText().toString());
                    param.setContent(villagePublishRetContent.getHtml());
                    param.setId(id);
                    param.setCategory(categroyId);
                    param.setAuthor(Constants.userId);
                    param.setLocation(villagePublishTvPosition.getText().toString());
                    param.setImg(ImgUtils.getImgsString(imgList));
                    imgList.clear();
                    mVIllageUpdateActiclePersemter.updateVillageArticle();
                }
                break;
            case R.id.tv_add_photo:
            case R.id.img_add_photo_litter:
                //选择图片
                Intent intent = new Intent(this, ImageGridActivity.class);
                imgList.clear();
                startActivityForResult(intent, IMAGE_PICKER);
                break;
            case R.id.village_publish_tv_select_type:
                //选择文章分类
                showPickerViewType(villagePublishTvSelectType);
                break;
            default:
                break;
        }
    }

    //选择文章分类信息
    public void showPickerViewType(final TextView tv) {
        typeList = new ArrayList<>();
        for (int i = 0; i < stringArray.length; i++) {
            typeList.add(stringArray[i]);
        }
        optionsPickerView = new OptionsPickerView.Builder(mContext, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String tx = typeList.get(options1);
                categroyId = options1 + 1;
                tv.setText(tx);
            }
        }).setTitleText("类型选择")
                .setDividerColor(Color.BLACK)
                .setTextColorCenter(Color.BLACK) //设置选中项文字颜色
                .setContentTextSize(20)
                .setOutSideCancelable(false)// default is true
                .build();
        optionsPickerView.setPicker(typeList);
        optionsPickerView.show();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == ImagePicker.RESULT_CODE_ITEMS) {
            if (data != null && requestCode == IMAGE_PICKER) {
                images.clear();
                images.addAll((ArrayList<ImageItem>) data.getSerializableExtra(ImagePicker.EXTRA_RESULT_ITEMS));
                if (images.size() > 0) {
                    villagePublishHsv.setVisibility(View.VISIBLE);
                    villagePublishTvPhoto.setVisibility(View.GONE);
                } else {
                    villagePublishHsv.setVisibility(View.GONE);
                    villagePublishTvPhoto.setVisibility(View.VISIBLE);
                }
                for (int i = 0; i < images.size(); i++) {
                    lubanImg(images.get(i).path);
                }
                photoAdapter = new VillagePublishHeaderPhotoAdapter(mContext, images, handler);
                villagePublishRecyPhoto.setAdapter(photoAdapter);
            } else {
                Toast.makeText(this, "请选择图片", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void lubanImg(String photos) {
        Luban.with(this)
                .load(photos)
                .setCompressListener(new OnCompressListener() { //设置回调
                    @Override
                    public void onStart() {
                        // 压缩开始前调用，可以在方法内启动 loading UI
                    }

                    @Override
                    public void onSuccess(File file) {
                        //  压缩成功后调用，返回压缩后的图片文件
                        photoParam = new UpLoadPhotoParam(file);
                        mUploadPhotosPersenter.uploadData();
                    }

                    @Override
                    public void onError(Throwable e) {
                        // 当压缩过程出现问题时调用
                    }
                }).launch();    //启动压缩
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            exitDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void setData(Object o) {
        if (o != null) {
            int successType = (int) o;
            if (successType == Constants.AddSuccess) {
                Toast.makeText(mContext, "发布成功", Toast.LENGTH_SHORT).show();
                finish();
                //发布成功
            } else if (successType == Constants.UpdateSuccess) {
                Toast.makeText(mContext, "更新成功", Toast.LENGTH_SHORT).show();
                this.setResult(resultCode);
                finish();
                //更改成功
            }
        }
    }

    @Override
    public void showLoading() {
        ProgressDialogHelper.show(mContext);
    }

    @Override
    public void hideLoading() {
        ProgressDialogHelper.dismissDialog();
    }

    @Override
    public void message(String str) {

    }

    @Override
    public VillageArticleParam addVillageArticle() {
        if (param == null) {
            return null;
        }
        return param;
    }

    @Override
    public VillageArticleParam updateVillageArticle() {
        if (param == null) {
            return null;
        }
        return param;
    }


    @Override
    public UpLoadPhotoParam uploadPhoto() {
        return photoParam;
    }


    @Override
    public void uploadData(String urls) {
        imgList.add(urls);
    }

}
